from typing import Optional

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
        self.val = val
        self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        carry = 0
        dummy_head = ListNode(0)
        current = dummy_head

        p = l1
        q = l2
        while p is not None or q is not None or carry != 0:
            x = p.val if p is not None else 0
            y = q.val if q is not None else 0
            total = x + y + carry
            carry = total // 10
            current.next = ListNode(total % 10)
            current = current.next
            p = p.next if p is not None else None
            q = q.next if q is not None else None

        return dummy_head.next

if __name__ == "__main__":
    def build_linked_list(nums):
        dummy = ListNode(0)
        cur = dummy
        for n in nums:
            cur.next = ListNode(n)
            cur = cur.next
        return dummy.next

    def linked_list_to_list(head: Optional[ListNode]):
        res = []
        while head is not None:
            res.append(head.val)
            head = head.next
        return res

    # 示例： [2,4,3] + [5,6,4] = [7,0,8]
    l1 = build_linked_list([2, 4, 3])
    l2 = build_linked_list([5, 6, 4])
    solution = Solution()
    result_head = solution.addTwoNumbers(l1, l2)
    print(linked_list_to_list(result_head))